<!--
 *                   江城子 . 程序员之歌
 *
 *               十年生死两茫茫，写程序，到天亮。
 *                   千行代码，Bug何处藏。
 *               纵使上线又怎样，朝令改，夕断肠。
 *
 *               领导每天新想法，天天改，日日忙。
 *                   相顾无言，惟有泪千行。
 *               每晚灯火阑珊处，夜难寐，加班狂。
 *
 *
 * @Descripttion:
 * @version:
 * @Date: 2022-03-02 13:50:45
 * @LastEditors: huzhushan@126.com
 * @LastEditTime: 2022-07-24 13:30:42
 * @Author: huzhushan@126.com
 * @HomePage: https://huzhushan.gitee.io/vue3-element-admin
 * @Github: https://github.com/huzhushan/vue3-element-admin
 * @Donate: https://huzhushan.gitee.io/vue3-element-admin/donate/
 -->

<template>
  <div class="app-container">
    <breadcrumb
      v-if="isComponent"
      type="directory"
      style="padding: 0; margin-top: -20px"
    />
    <pro-table
      ref="pageBox"
      :class="{ 'thumbnail-mode': view_mode === 'THUMBNAIL' }"
      title="媒体库"
      :request="getList"
      :columns="columns"
      :search="searchObj"
      @selectionChange="handleSelectionChange"
    >
      <template v-if="!isComponent" #toolbar>
        <el-button
          icon="el-icon-plus"
          type="primary"
          @click="handleEditFolder()"
        >
          创建文件夹
        </el-button>
        <el-upload
          class="upload"
          style="display: inline-block; margin: 0 10px"
          action=""
          multiple
          :limit="10"
          :show-file-list="false"
          :http-request="handleUploadFile"
        >
          <el-button icon="el-icon-plus" type="primary">上传文件</el-button>
        </el-upload>

        <el-button
          :disabled="selectedArr.length <= 0"
          icon="el-icon-delete"
          @click="handleDelete"
        ></el-button>
        <el-button :disabled="selectedArr.length <= 0" @click="handleMove">
          <svg-icon icon-class="link" style="width: 0.9em; height: 0.9em" />
        </el-button>
      </template>
      <template #expand="{ row }">
        <el-card shadow="never">id：{{ row.id }}</el-card>
      </template>

      <template #media_name="{ row }">
        <el-button type="text" @click="handleClickRow(row)">
          <i :class="`el-icon-${iconType[+row.media_type]}`" />
          {{ row.media_name }}
        </el-button>
      </template>
      <template #status="{ row }">
        <el-tag size="mini" :type="statusType[+row.status].type" effect="dark">
          {{ statusType[+row.status].msg }}
        </el-tag>
      </template>
      <template #date="{ row }">
        {{ row.create_time | parseTime }}
      </template>
      <template #size="{ row }">
        <span v-if="+row.media_type !== 1">
          {{ Math.round((row.file_size / 1024) * 10) / 10 }}k
        </span>
      </template>

      <template #operate="{ row }">
        <el-tooltip v-if="+row.media_type === 1" content="编辑" placement="top">
          <i
            class="el-icon-edit operate-button"
            @click="handleEditFolder(row)"
          ></i>
        </el-tooltip>
        <el-tooltip v-else content="移动到..." placement="top">
          <svg-icon
            icon-class="link"
            class="operate-button"
            @click="handleMove([row])"
          />
        </el-tooltip>
        <el-divider direction="vertical" class="button-divider"></el-divider>
        <el-tooltip content="删除" placement="top">
          <i
            class="el-icon-delete operate-button"
            @click="handleDelete([row])"
          ></i>
        </el-tooltip>
      </template>

      <template #prev>
        <el-button
          v-if="path && path !== '/'"
          style="margin-right: 10px"
          type="text"
          @click="handlePrev"
        >
          返回上一级
        </el-button>
        <el-radio-group
          v-model="view_mode"
          style="vertical-align: 5px"
          @change="handleViewModeChange"
        >
          <el-tooltip placement="top" content="缩略图模式" :tabindex="-1">
            <el-radio-button label="THUMBNAIL" :tabindex="-1">
              <i class="el-icon-picture-outline"></i>
            </el-radio-button>
          </el-tooltip>
          <el-tooltip v-if="!isComponent" placement="top" content="列表模式">
            <el-radio-button label="TABLE">
              <svg-icon
                icon-class="list"
                style="width: 0.8em; height: 0.8em; vertical-align: unset"
              />
            </el-radio-button>
          </el-tooltip>
        </el-radio-group>
      </template>
    </pro-table>
    <div
      v-if="view_mode === 'THUMBNAIL'"
      v-loading="loading"
      class="thumbnail-box"
    >
      <div
        v-for="item in list"
        :key="item.id"
        class="thumbnail-item"
        @click="handleClickRow(item)"
      >
        <div
          v-if="
            +item.media_type === 1 ||
              +item.media_type === 3 ||
              +item.media_type === 4
          "
        >
          <i :class="`el-icon-${iconType[+item.media_type]}`"></i>
          <p>{{ item.media_name }}</p>
        </div>
        <img
          v-else-if="+item.media_type === 2 || +item.media_type === 5"
          :src="item.media_url"
        />
        <div v-if="!isComponent" class="btns" @click.stop="() => {}">
          <template v-if="+item.media_type === 2 || +item.media_type === 5">
            <el-tooltip content="拷贝链接" placement="top">
              <i
                class="el-icon-copy-document operate-button"
                @click.stop="handleCopy(item.media_url, $event)"
              />
            </el-tooltip>
            <el-divider
              direction="vertical"
              class="button-divider"
            ></el-divider>
            <el-tooltip content="下载" placement="top">
              <i
                class="el-icon-download operate-button"
                @click.stop="handleDownload(item.media_url)"
              />
            </el-tooltip>
            <el-divider
              direction="vertical"
              class="button-divider"
            ></el-divider>
          </template>

          <el-tooltip
            v-if="+item.media_type === 1"
            content="编辑"
            placement="top"
          >
            <i
              class="el-icon-edit operate-button"
              @click.stop="handleEditFolder(item)"
            ></i>
          </el-tooltip>
          <el-tooltip v-else content="移动到..." placement="top">
            <svg-icon
              icon-class="link"
              class="operate-button"
              @click.stop="handleMove([item])"
            />
          </el-tooltip>
          <el-divider direction="vertical" class="button-divider"></el-divider>
          <el-tooltip content="删除" placement="top">
            <i
              class="el-icon-delete operate-button"
              @click.stop="handleDelete([item])"
            ></i>
          </el-tooltip>
        </div>
      </div>
    </div>
    <!-- 移动目录弹窗 -->
    <el-dialog
      title="移动到..."
      :visible.sync="showMoveDialog"
      width="400px"
      :destroy-on-close="true"
      :close-on-click-modal="false"
    >
      <el-select v-model="selectedFolder" style="width: 100%">
        <el-option
          v-for="item in folderList"
          :key="item.id"
          :label="item.folder_path"
          :value="item.folder_path"
        ></el-option>
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showMoveDialog = false">取 消</el-button>
        <el-button
          v-loading="moveLoading"
          type="primary"
          @click="handleSubmitMove"
        >
          确 定
        </el-button>
      </span>
    </el-dialog>
    <!-- 查看图片等抽屉式弹窗 -->
    <el-drawer
      :append-to-body="true"
      :wrapper-closable="false"
      :show-close="false"
      :with-header="false"
      :visible.sync="showViewModal"
      direction="rtl"
      size="640px"
    >
      <drawer-frame
        :show-submit="false"
        cancel-text="关闭"
        @close="showViewModal = false"
      >
        <template #title>
          <span>
            <!-- <i
              :class="`el-icon-${iconType[selectedMedia.type]}`"
              style="cursor: default"
            /> -->
            {{ selectedMedia.media_name }}
          </span>
        </template>
        <div v-if="+selectedMedia.media_type === 2">
          <div style="margin-bottom: 20px; text-align: center">
            <el-button
              v-if="isComponent"
              type="success"
              @click="handleSelectPic(selectedMedia.media_url)"
            >
              使用这个图片
            </el-button>
            <el-button
              type="primary"
              @click="handleCopy(selectedMedia.media_url, $event)"
            >
              拷贝链接
            </el-button>
            <el-button
              type="primary"
              @click="handleDownload(selectedMedia.media_url)"
            >
              下载
            </el-button>
          </div>
          <img
            :src="selectedMedia.media_url"
            alt=""
            style="max-width: 100%; margin: 0 auto; display: block"
          />
        </div>
      </drawer-frame>
    </el-drawer>
  </div>
</template>
<script>
import {
  GetList,
  DeleteItem,
  DeleteFolder,
  GetFolderList,
  FileMove,
  FolderAdd,
  FolderUpdate,
  FileAdd,
} from '@/api/media'
import Breadcrumb from '@/components/Breadcrumb'
import clip from '@/utils/clipboard'
export default {
  name: 'Medias',
  components: {
    Breadcrumb,
  },
  data() {
    return {
      statusType: {
        1: { msg: '审核通过', type: 'success' },
        2: { msg: '审核拒绝', type: 'danger' },
        3: { msg: '待审核', type: 'warning' },
      },
      moveLoading: false,
      isComponent: this.$route.name !== 'Medias',
      showViewModal: false,
      selectedMedia: {},
      loading: false,
      list: [],
      view_mode:
        this.$route.name !== 'Medias'
          ? 'THUMBNAIL'
          : localStorage.MEDIA_EXPLORER_VIEW_MODE || 'TABLE',
      path: localStorage.MEDIA_EXPLORER_PATH || '',
      showMoveDialog: false,
      folderList: [],
      selectedFolder: '/',
      toMoveItems: [],
      iconType: {
        1: 'folder-opened',
        2: 'picture-outline',
        3: 'microphone',
        4: 'video-camera',
        5: 'picture-outline-round',
      },
      selectedArr: [],
      columns: [
        // { type: 'expand', tdSlot: 'expand' },
        { type: 'selection', selectable: row => +row.media_type !== 1 },
        {
          label: '名称',
          tdSlot: 'media_name',
          minWidth: 400,
        },
        {
          label: '审核意见',
          prop: 'info',
          wrap: true,
          minWidth: 200,
        },
        {
          label: '审核状态',
          tdSlot: 'status',
          align: 'center',
          minWidth: 120,
        },
        {
          label: '文件大小',
          tdSlot: 'size',
          align: 'center',
        },
        {
          label: '创建时间',
          tdSlot: 'date',
          align: 'center',
          width: 160,
        },
        {
          label: '操作',
          tdSlot: 'operate',
          width: 120,
          align: 'center',
          fixed: 'right',
        },
      ],
      searchObj: {
        inputWidth: '160px',
        fields: [
          { type: 'custom', slot: 'prev' },
          {
            type: 'select',
            label: '类型',
            name: 'media_type',
            options: [
              {
                name: '文件夹',
                value: 1,
              },
              {
                name: '图片',
                value: 2,
              },
              {
                name: '音频',
                value: 3,
              },
              {
                name: '视频',
                value: 4,
              },
              {
                name: '缩略图',
                value: 5,
              },
            ],
          },
          {
            type: 'text',
            label: '名称',
            name: 'media_name',
          },
        ],
      },
    }
  },

  created() {
    window.addEventListener('setItemEvent', this.handleChangeStorage)
  },
  beforeDestroy() {
    window.removeEventListener('setItemEvent', this.handleChangeStorage)
  },
  methods: {
    handleCopy(text, event) {
      clip(text, event)
    },
    handleDownload(url) {
      window.open(url)
    },
    async handleUploadFile(params) {
      const file = params.file
      const forms = new FormData() // 实例化一个formData，用来做文件上传
      forms.append('file', file)
      forms.append('file_name', file.name)
      forms.append('cur_path', this.path)
      await FileAdd(forms)
      this.refresh()
    },
    handleChangeStorage(e) {
      if (e.key === 'MEDIA_EXPLORER_PATH') {
        this.$nextTick(() => {
          this.path = localStorage.MEDIA_EXPLORER_PATH
          this.getData()
        })
      }
    },
    handleMove(arr) {
      this.toMoveItems = Array.isArray(arr) ? arr : this.selectedArr
      this.getFolders()
      this.showMoveDialog = true
    },

    async handleSubmitMove() {
      // console.log(this.toMoveItems, this.selectedFolder)
      this.moveLoading = true
      const { code, msg } = await FileMove({
        cur_path: this.path,
        file_id: this.toMoveItems.map(item => item.media_id).join(','),
        new_path: this.selectedFolder,
      })
      this.moveLoading = false
      if (+code === 1) {
        this.$message.success(msg)
        this.$refs.pageBox.refresh()
        this.showMoveDialog = false
      } else {
        this.$message.error(msg)
      }
    },
    async getFolders() {
      const { code, data } = await GetFolderList()
      this.folderList = +code === 1 ? data : []
    },
    async getList(params) {
      const body = {
        ...params,
        pageSize: this.view_mode === 'THUMBNAIL' ? 1000 : params.pageSize,
      }
      // console.log(body)
      this.loading = true
      const { pageNum: page, pageSize: rows, ...rest } = body
      const { code, data } = await GetList({
        cur_path: localStorage.MEDIA_EXPLORER_PATH,
        page,
        rows,
        ...rest,
      })
      // const { code, data } = await new Promise(resolve => {
      //   setTimeout(() => {
      //     resolve({
      //       code: 200,
      //       data: {
      //         list: [
      //           {
      //             createTime: '2022-03-10T02:02:53.000+0000',
      //             enterpriseId: '141598637888113837',
      //             id: '218026893725663593',
      //             name: 'cccc',
      //             path: '/',
      //             size: 0,
      //             type: 'FOLDER',
      //           },
      //           {
      //             auditRemark:
      //               'AI 审核不通过，等待人工审核，原因是Open api qps request limit reached',
      //             auditStatus: 'PENDING',
      //             contentType: 'image/jpeg',
      //             createTime: '2022-03-10T02:11:30.000+0000',
      //             enterpriseId: '141598637888113837',
      //             id: '218026893725663606',
      //             name: '20190908141144-915986b9.jpeg',
      //             path: '/',
      //             size: 224817,
      //             thumbUrl:
      //               'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif?imageView2/1/w/80/h/80',
      //             type: 'IMAGE',
      //             url: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif?imageView2/1/w/80/h/80',
      //           },
      //         ],
      //         total: 100,
      //       },
      //     })
      //   }, 500)
      // })
      this.loading = false
      if (+code === 1) {
        this.list = data.list
        return {
          data: data.list,
          total: +data.total,
        }
      }
      this.list = []
      return {
        data: [],
        total: 0,
      }
    },
    handleViewModeChange() {
      localStorage.setItem('MEDIA_EXPLORER_VIEW_MODE', this.view_mode)
      this.$refs.pageBox.handleSearch()
    },
    handleSelectionChange(arr) {
      this.selectedArr = arr
    },
    handleEditFolder(row) {
      this.$prompt('', '创建文件夹', {
        inputPattern: /^[^\/\s][^\/]*[^\/]?$/,
        inputErrorMessage: '文件夹格式不正确',
        inputValue: row ? row.media_name : '',
        inputPlaceholder: '请输入文件夹名称',
        center: true,
        closeOnClickModal: false,
        iconClass: 'el-icon-folder warning',
      })
        .then(async ({ value }) => {
          console.log(2323, row)
          if (row) {
            const { code, msg } = await FolderUpdate({
              cur_path: this.path,
              folder_name: row.media_name,
              folder_new: value,
            })
            if (+code === 1) {
              this.$message.success(msg)
              this.refresh()
            } else {
              this.$message.error(msg)
            }
          } else {
            const { code, msg } = await FolderAdd({
              cur_path: this.path,
              folder_name: value,
            })
            if (+code === 1) {
              this.$message.success(msg)
              this.refresh()
            } else {
              this.$message.error(msg)
            }
          }
        })
        .catch(() => {})
    },
    refresh() {
      // console.log(this.$refs.pageBox)
      this.$refs.pageBox.refresh()
    },
    async handleDelete(items) {
      this.$confirm(
        '选定的条目及条目相关的数据将被删除且不可恢复，您是否确定删除？',
        '删除',
        {
          iconClass: 'el-icon-warning-outline warning',
          center: true,
          closeOnClickModal: false,
        }
      ).then(async () => {
        const arr = Array.isArray(items) ? items : this.selectedArr
        const { code, msg } =
          arr.length === 1 && +arr[0].media_type === 1
            ? await DeleteFolder({
              folder_name: arr[0].media_name,
              cur_path: localStorage.MEDIA_EXPLORER_PATH,
            })
            : await DeleteItem({
              file_id: arr.map(item => item.media_id).join(','),
            })
        if (+code === 1) {
          this.$message.success(msg)
          this.refresh()
        } else {
          this.$message.error(msg)
        }
      })
    },
    handlePrev() {
      const MEDIA_EXPLORER_PATH = localStorage.MEDIA_EXPLORER_PATH
      if (!MEDIA_EXPLORER_PATH || MEDIA_EXPLORER_PATH === '/') {
        return
      }
      const path = MEDIA_EXPLORER_PATH.replace(/[^\/]+\/$/, '')
      localStorage.setItem('MEDIA_EXPLORER_PATH', path)
      this.$breadcrumb.getBreadcrumb()
    },
    handleClickRow(row) {
      if (+row.media_type === 1) {
        localStorage.setItem(
          'MEDIA_EXPLORER_PATH',
          `${this.path}${row.media_name}/`
        )
        this.$breadcrumb.getBreadcrumb()
      } else {
        this.selectedMedia = row
        this.showViewModal = true
      }
    },

    getData() {
      console.log(`获取${localStorage.MEDIA_EXPLORER_PATH || '/'}的数据`)
      this.$refs.pageBox.handleReset()
    },
    handleSelectPic(url) {
      this.showViewModal = false
      this.$emit('select', url)
    },
  },
}
</script>
<style lang="scss" scoped>
.thumbnail-mode {
  ::v-deep {
    .table,
    .pagination {
      display: none;
    }
  }
}
.thumbnail-box {
  min-height: 200px;
  display: flex;
  flex-wrap: wrap;
  margin: -10px;
  .thumbnail-item {
    width: 190px;
    height: 190px;
    margin: 10px;
    padding: 1px;
    border: 1px solid rgb(221, 221, 221);
    border-radius: 4px;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    color: $primary;
    text-align: center;
    position: relative;
    [class^='el-icon'] {
      font-size: 64px;
      opacity: 0.7;
    }
    img {
      max-width: 100%;
      max-height: 100%;
    }
    .btns {
      display: none;
      position: absolute;
      bottom: 1px;
      left: 1px;
      right: 1px;
      padding: 8px;
      background: rgba(0, 0, 0, 0.6);
      .operate-button {
        color: #fff;
      }
    }
    &:hover .btns {
      display: block;
    }
  }
}
</style>
